<?php

namespace App\Observers;

use App\Models\Common\Area\Area;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class AreaObserver
{

    /**
     * @throws Exception
     */
    public function creating(Area $area)
    {
        $area->letter = Str::upper($area->letter);
        if (!in_array($area->level, $area::SUPPORT_LEVELS)) {
            throw new Exception("{$area->name}:creating不支持的地区等级-{$area->level}");
        }
        $area->type = $this->updateAreaType($area);
    }

    private function updateAreaType(Area &$area)
    {
        $configAreaTypes                 = config('area.area_types');
        $configAreaMunicipalityDistricts = config('area.municipality.district');
        return $configAreaTypes[$area->adcode] ?? (in_array($area->name, $configAreaMunicipalityDistricts) ? 3 : 0);
    }

    public function updating(Area $area)
    {
        $area->letter = Str::upper($area->letter);
        if (!in_array($area->level, $area::SUPPORT_LEVELS)) {
            throw new Exception("{$area->name}:updating不支持的地区等级-{$area->level}");
        }
        $area->type = $this->updateAreaType($area);
    }

    public function created(Area $area)
    {
        $cache_key = "Area:code:{$area->adcode}";

        // 这里将火车站的 经纬度 存到 redis members 用户定位最近火车站~~

        Cache::forever($cache_key, $area);
    }

    public function updated(Area $area)
    {
        $cache_key = "Area:code:{$area->adcode}";
        Cache::forever($cache_key, $area);
    }

    public function saved(Area $area)
    {
        $cache_key = "Area:code:{$area->adcode}";
        Cache::forever($cache_key, $area);
    }

    public function deleted(Area $area)
    {
        $cache_key = "Area:code:{$area->adcode}";
        Cache::forget($cache_key);
    }
}
